// pages/goods/index.js
const api = require('../../utils/request')
const utils = require('../../utils/util')
const WxParse = require('../../libs/wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    loading: true,
    showSku:false,
    sku:{},
    skuSel: {
      num:1
    },
    goods: {},
    chooseAttrText: {},
    attrText:'',
    buyOrAddCart: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id=options.id;
    this.setData({
      id
    })
    this.getGoods(id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getGoods(id){
    api.get('/goods/' + id).then(res=>{
      let goods = res.goods
      /*
      res.sku=Object.assign({},res.sku,{
        "tree":[
          {
              "k_s":"s1",
              "k":"版本",
              "v":[
                  {
                      "id":"1",
                      "name":"3GB+32GB"
                  },
                  {
                      "id":"2",
                      "name":"4GB+64GB"
                  }
              ]
          },
          {
              "k_s":"s2",
              "k":"颜色",
              "v":[
                  {
                      "id":"3",
                      "name":"珊瑚橙"
                  },
                  {
                      "id":"4",
                      "name":"深海蓝"
                  }
              ]
          }
        ],
        "list":[
            {
                "price":69900,
                "id":"1",
                "s1":"1",
                "s2":"3",
                "stock_num":100 
            },
            {
                "price":69900,
                "id":"2",
                "s1":"1",
                "s2":"4",
                "stock_num":100
            },
            {
                "price":74900,
                "id":"3",
                "s1":"2",
                "s2":"3",
                "stock_num":100
            },
            {
                "price":74900,
                "id":"4",
                "s1":"2",
                "s2":"4",
                "stock_num":100
            }
        ],
        "stock_num":400,
        "none_sku":false,
        "price":69900,
      });
      */
      // 分别给 sku.tree list 添加sel 选中属性
      if(res.sku.tree){
        res.sku.tree.forEach(item=>{
          if(item && item.v){
            item.v.forEach((itemV)=>{
              itemV.sel=false
            })
          }
        })
      }

      // tree 例如 [{'k_s':'s1','k':'版本','v':[{'id':'1','name':'3GB+32GB'}]}]
      let chooseAttrText = {} // [{'s1':'版本','s2':'颜色'}]
      for (let i = 0; i < res.sku.tree.length; i++) {
        chooseAttrText[res.sku.tree[i]['k_s']] = res.sku.tree[i].k
      }
      let ret=''
      if (!res.sku.none_sku) {
        ret = '选择： '
        for (let key in chooseAttrText) {
          ret += chooseAttrText[key] + ' '
        }
        
      }
      goods.thumb = []
      const gallery = goods.gallery.split(',')
      for (const index in gallery) {
        goods.thumb.push({imgUrl: utils.fileMgrUrl + gallery[index]})
      }
      goods.imgUrl = utils.fileMgrUrl + goods.pic
      this.setData({
        sku: res.sku,
        goods,
        chooseAttrText,
        attrText: ret,
        loading: false,
        skuSel: {
          id: res.sku.collection_id,
          stock_num: res.sku.stock_num,
          price: res.sku.price
        }
      },()=>{
        WxParse.wxParse('goodsDetail', 'html', goods.detail, this);
      })
    })
  },
  customerHandle(){
    console.log('customer...');
  },
  openCartHandle(){
    wx.switchTab({
      url: '/pages/cart/index',
    })
  },
  addToCartHandle(){
    // 没登录就跳转登录页面
    if(utils.loginNow()){
      this.setData({
        showSku: true,
        buy: false
      })
    }
  },
  buyNowHandle(){
    if(utils.loginNow()){
      this.setData({
        showSku: true,
        buy: true
      })
    }
  },
  buyHandle(){
    if(!this.data.skuSel.ks || Object.keys(this.data.skuSel.ks).length !== this.data.sku.tree.length){
      wx.showToast({
        title: this.data.attrText,
        duration: 3000
      })
      return
    }

    wx.showLoading()
    api.post('/user/cart/add',{count:1,idGoods: this.data.id,idSku: this.data.skuSel.id}).then(_=>{
      wx.hideLoading();
      this.setData({
        showSku: false,
        buy: false
      },()=>{
        wx.switchTab({
          url: '/pages/cart/index',
        })
      })
    })
  },
  addHandle(){
    if(!this.data.skuSel.ks || Object.keys(this.data.skuSel.ks).length !== this.data.sku.tree.length){
      wx.showToast({
        title: this.data.attrText,
        duration: 3000
      })
      return
    }

    wx.showLoading({
      title: '正在加入购物车',
    })
    api.post('/user/cart/add',{count:1,idGoods: this.data.id,idSku: this.data.skuSel.id}).then(_=>{
      wx.hideLoading();
      wx.showToast({
        title: '加入购物车成功',
      })
      this.setData({
        showSku: false,
        buy: false
      })
    })
  },
  closeSkuView(){
    this.setData({
      showSku: false
    })
  },
  chooseAttr(e) {
    const {n,v} = e.currentTarget.dataset
    console.log(n,v)
    const sku = {...this.data.sku}
    if(sku.tree){
      sku.tree.forEach(item=>{
        if(item.k_s == n.k_s){
          if(item.v){
            item.v.forEach((itemV)=>{
              if(itemV.id == v.id ){
                itemV.sel=true
              }else{
                itemV.sel=false
              }
            })
          }
        }
      })
    }
    // {s1:s1_id,s2:s2_id} k_s : id
    const skuSel = this.data.skuSel ? {...this.data.skuSel}:{}
    const ks = skuSel.ks ? skuSel.ks: [];
    if(!ks.includes(n['k_s'])){
      ks.push(n['k_s'])
    }
    skuSel.ks=ks
    skuSel[n['k_s']] = v['id']
    
    if(Object.keys(skuSel.ks).length === sku.tree.length && sku.list){
      sku.list.forEach(item=>{
        const flag = skuSel['ks'].every(selItem=>{
          if(skuSel[selItem] === item[selItem] ){
            return true
          }else {
            return false
          }
        })
        if(flag){
          skuSel.id=item.id;
          skuSel.price=item.price;
          skuSel.stock_num=item.stock_num
        }
      })
    }


    this.setData({
      sku: sku,
      skuSel: skuSel
    })
  },
})